/**
 * $Id$
 *
 * Unpublished Work Copyright 2013 Confirmit, Inc. All Rights Reserved.
 *
 * Last changed by $Author$
 * Last changed at $Date$
 */
package com.youtills.core.web;

import com.youtills.core.lang.InstanceMaker;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @author Ravi Kumar Chiluveru (ravic)
 * @since 12.2, (5/18/13 2:12 PM)
 */
public class YoutillsDispatcherServlet extends HttpServlet {

    private static Map<String, String> URLS = new HashMap<String, String>();
    private final InstanceMaker<IRequestHandler> maker = new InstanceMaker<IRequestHandler>();

    public YoutillsDispatcherServlet(){
        URLS.put("/", "com.youtills.core.app.www.HomeRequestHandler");
        URLS.put("/bmi", "com.youtills.core.app.calc.BmiRequestHandler");
        URLS.put("/404", "com.youtills.core.app.common.Page404RequestHandler");
        URLS.put("/whoami", "com.youtills.core.app.dev.WhoAmIRequestHandler");
        URLS.put("/loan-calc", "com.youtills.core.app.calc.LoanCalcRequestHandler");
        URLS.put("/base64", "com.youtills.core.app.dev.Base64RequestHandler");
        URLS.put("/hex", "com.youtills.core.app.dev.HexRequestHandler");
        URLS.put("/random", "com.youtills.core.app.dev.RandomRequestHandler");
        URLS.put("/pcc-ev", "com.youtills.core.app.pcc.PccEvRequestHandler");

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        final String path = req.getServletPath();

        if(isMediaItem(path)){
            forwardToDefault(req, resp, getServletContext());
        } else {
            String handlerClass = URLS.get(path);
            if(handlerClass != null){
                IRequestHandler handler = maker.getInstanceOf(handlerClass);
                ContextBean contextBean = new ContextBean(req, resp, getServletContext());
                handler.setContextBean(contextBean);
                IResponse response = handler.handleRequest();
                req.setAttribute("handler", handler);
                try {
                    response.processResponse(req, resp, getServletContext());
                } catch (Exception e) {
                    throw new ServletException(e);
                }
            }else{
//                resp.sendRedirect("/404");
                req.setAttribute("originalURL", req.getRequestURL());
                req.getRequestDispatcher("/404").forward(req, resp);
            }
        }
    }

    private static boolean isMediaItem(String path){
        if(path != null){
            String lPath = path.toLowerCase();
            return lPath.endsWith(".css")
                    || lPath.endsWith(".jpg")
                    || lPath.endsWith(".gif")
                    || lPath.endsWith(".png")
                    || lPath.endsWith(".js");
        }

        return false;
    }

    private static void forwardToDefault(HttpServletRequest req, HttpServletResponse resp, ServletContext context) throws IOException, ServletException {
        RequestDispatcher rd = context.getNamedDispatcher("default");

        HttpServletRequest wrapped = new HttpServletRequestWrapper(req);

        rd.forward(wrapped, resp);
    }
}
